<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="400px" append-to-body custom-class="import-dialog">
      <div v-loading="loading">
        <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="id" :check-strictly="false"
          empty-text="加载中，请稍候" :props="defaultProps"></el-tree>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { treeselect as menuTreeselect, depMenuTreeselect, editMenuByDep } from "@/api/sys-enterprise";
export default {
  props: {
    title: {
      default: "企业权限设置",
    },
    value: {
      default: false,
    },
    tenantId: {
      default: undefined,
    },
  },
  dicts: [],
  data() {
    return {
      visible: false,
      form: {},
      rules: {},
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      //列表
      list: [],
    };
  },
  watch: {
    value(newVal, oldVal) {
      if (newVal) {
        this.init();
      }
      this.visible = newVal; // 监测value的变化，并赋值。
    },
    visible(val) {
      this.$emit("input", val); // 此处监测visible目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    },
  },
  methods: {
    init() {
      // this.reset()
      this.getDepMenuTreeselect()
    },
    /** 查询菜单树结构 */
    getDepMenuTreeselect() {
      depMenuTreeselect(this.tenantId).then(response => {
        this.menuOptions = response.menus;
        let checkedKeys = response.menuIdsByDep
        checkedKeys.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, true, false);
          })
        })
      });
    },
    reset() {
      this.form = {}
      this.resetForm("form");
    },
    // 所有部门节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    submitForm() {
      let data = {
        tenantId:this.tenantId,
        menuIds:this.getMenuAllCheckedKeys()
      }
      editMenuByDep(data).then(response => {
        if(response.code==200){
          this.$message.success(response.msg);
          this.visible = false;
        }
      })
    },
    cancel() {
      this.reset();
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/dialog.scss";
</style>
